package com.yxx.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxx.constant.RedisConstant;
import com.yxx.entity.SiteConfig;
import com.yxx.enums.FilePathEnum;
import com.yxx.mapper.SiteConfigMapper;
import com.yxx.service.BlogFileService;
import com.yxx.service.RedisService;
import com.yxx.service.SiteConfigService;
import com.yxx.strategy.context.UploadStrategyContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 网站配置服务实现类
 * @author yuxiangxun
 * @date 2025/1/26
 * @apiNote
 */
@Service
@Slf4j
public class SiteConfigServiceImpl extends ServiceImpl<SiteConfigMapper, SiteConfig> implements SiteConfigService {
    @Resource
    private RedisService redisService;

    @Resource
    private SiteConfigMapper siteConfigMapper;

    @Resource
    private UploadStrategyContext uploadStrategyContext;

    @Resource
    private BlogFileService blogFileService;

    /**
     * 获取网站配置
     * @return
     */
    @Override
    public SiteConfig getSiteConfig() {
        // 从 Redis 中获取网站配置
        SiteConfig siteConfig = redisService.getObject(RedisConstant.SITE_SETTING);
        // 如果 Redis 中没有网站配置数据，则从数据库中获取
        if(ObjectUtil.isNull(siteConfig)){
            siteConfig = siteConfigMapper.selectById(1);
            log.info("从数据库中获取siteConfig:{}",siteConfig);
            // 从数据库中获取到网站配置信息后，缓存到 Redis 中
            redisService.setObject(RedisConstant.SITE_SETTING, siteConfig);
        }
        return siteConfig;
    }

    /**
     * 更新网站配置
     * @param siteConfig
     */
    @Override
    public void updateSiteConfig(SiteConfig siteConfig) {
        // 更新数据库网站配置信息
        baseMapper.updateById(siteConfig);
        // 删除 Redis 中的网站配置数据  因为网站配置信息改变，所以需要重新获取
        redisService.deleteObject(RedisConstant.SITE_SETTING);
    }

    /**
     * 上传网站配置图片
     * @param file
     * @return
     */
    @Override
    public String uploadSiteImg(MultipartFile file) {
        // 选择上传策略上下文选择某种策略上传图片文件
        String url = uploadStrategyContext.executeUploadStrategy(file, FilePathEnum.CONFIG.getPath());
        // 保存图片到数据库
        blogFileService.saveBlogFile(file,url,FilePathEnum.CONFIG.getFilePath());
        return url;
    }
}
